package com.uziot.bucket.common.socket;

import com.uziot.bucket.common.util.StreamUtils;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author Lenovo
 * Socket服务接收到请求后的单独处理任务线程，服务继续监听
 */
public class ResponseThread extends Thread {

    private final Socket socket;

    public ResponseThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        BufferedReader bufferedReader = null;
        OutputStream outputStream = null;
        BufferedWriter bufferedWriter = null;
        //接收客户端请求信息
        try {
            inputStream = socket.getInputStream();
            bufferedReader = new BufferedReader(
                    new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            String info = bufferedReader.readLine();
            while (info != null) {
                System.out.println("客户端发送信息为：" + info);
                info = bufferedReader.readLine();
            }

            //响应客户端信息
            outputStream = socket.getOutputStream();
            bufferedWriter = new BufferedWriter(
                    new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
            bufferedWriter.write("服务器响应的信息为：欢迎您！！！");
            bufferedWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            StreamUtils.close(bufferedWriter);
            StreamUtils.close(outputStream);
            StreamUtils.close(bufferedReader);
            StreamUtils.close(inputStream);
            try {
                socket.shutdownInput();
            } catch (IOException ignored) {
            }
            try {
                socket.close();
            } catch (IOException ignored) {
            }
        }
    }


}